<template>
  <n-modal
    v-model:show="showModal"
    :show-icon="false"
    preset="dialog"
    :title="title"
    :style="{ width: props.width + 'px' }"
    @update:show="handleUpdateShow"
  >
    <n-spin :show="modalLoading" content-class="max-h-[80vh] overflow-auto pr-2">
      <n-form :model="formData" :rules="formRules" ref="formRef" label-width="auto" label-placement="top">
        <n-grid :cols="2" :x-gap="24">
          <n-form-item-gi span="2" label="角色名称" path="roleNm">
            <n-input placeholder="请输入角色名称" v-model:value="formData.roleNm" />
          </n-form-item-gi>
          <n-form-item-gi span="2" label="权限编码" path="roleCd">
            <div class="w-full">
              <div><n-input placeholder="请输入权限编码" v-model:value="formData.roleCd" :disabled="formData.roleCd === 'DEFAULT'" /></div>
              <div class="flex items-center text-xs text-slate-500 pt-1">
                <n-icon :size="14" :component="InfoCircleFilled" /><span class="pl-1">控制器中定义的权限编码，如：@RequiresRoles("")</span>
              </div>
            </div>
          </n-form-item-gi>
          <n-form-item-gi span="2" label="角色类型" path="roleTpCd">
            <n-radio-group v-model:value="formData.roleTpCd" name="radiogroup">
              <n-space>
                <n-radio v-for="roleTp in roleTpList" :key="roleTp.value" :value="roleTp.value">
                  {{ roleTp.label }}
                </n-radio>
              </n-space>
            </n-radio-group>
          </n-form-item-gi>
          <n-form-item-gi span="2" path="dfltFlg" :show-label="false">
            <n-checkbox checked-value="Y" unchecked-value="N" @update:checked="handleUpdateDfltFlg"> 默认角色 </n-checkbox>
          </n-form-item-gi>
          <n-form-item-gi span="2" label="备注" path="rmrk">
            <n-input placeholder="请输入备注" v-model:value="formData.rmrk" type="textarea" :autosize="{ minRows: 3, maxRows: 5 }" />
          </n-form-item-gi>
        </n-grid>
      </n-form>
    </n-spin>
    <template #action>
      <n-space>
        <n-button @click="() => handleUpdateShow(false)">取消</n-button>
        <n-button v-if="hasPermission('bmpch:role:save', '保存角色')" type="info" :loading="saveBtnLoading" @click="handleSave">
          <template #icon>
            <n-icon>
              <SaveOutlined />
            </n-icon>
          </template>
          保存
        </n-button>
      </n-space>
    </template>
  </n-modal>
</template>

<script lang="ts" setup>
import { reactive, ref, unref, watch } from 'vue';
import type { FormRules, FormInst } from 'naive-ui';
import { SaveOutlined } from '@vicons/antd';
import type * as BMPCH from '@yanfan/bmpch-tsapi/types';
import { roleGet, roleSav } from '@yanfan/bmpch-tsapi/role';
import { InfoCircleFilled } from '@vicons/antd';
import { usePermission } from '@yanfan/common/hooks';

defineOptions({
  name: 'BmpchRoleEdit',
  titl: '角色编辑',
});

const props = withDefaults(
  defineProps<{
    show: boolean;
    width?: number;
    bizId: string | null;
  }>(),
  {
    show: false,
    width: 530,
  },
);

const emits = defineEmits<{
  (e: 'update:show', show: boolean): void;
  (e: 'refresh'): void;
}>();

const roleTpList = [
  { label: '管理员角色', value: 'Admin' },
  { label: '普通角色', value: 'General' },
];

class FormData {
  roleId: string = '';
  roleCd: string = '';
  roleNm: string = '';
  roleTpCd: string = '';
  roleClzCd: string = '';
  dfltFlg: string = 'N';
  chnlId: string = '';
  sysId: string = '';
  rmrk: string = '';
  delFlg: number = 0;
}

const formRules: FormRules = {};

const { hasPermission } = usePermission();
const modalLoading = ref(false);
const title = ref('新建');
const formRef = ref<FormInst | null>(null);
const showModal = ref(false);
const saveBtnLoading = ref(false);
const formData = reactive(new FormData());

watch(
  () => unref(props).show,
  (show) => {
    showModal.value = show;
    if (showModal.value) {
      if (props.bizId) {
        title.value = '编辑';
        modalLoading.value = true;
        roleGet({ roleId: props.bizId })
          .then((data: BMPCH.RoleGetOutput) => {
            Object.assign(formData, data);
          })
          .finally(() => {
            modalLoading.value = false;
          });
      } else {
        title.value = '新建';
        Object.assign(formData, new FormData());
      }
    } else {
      Object.assign(formData, new FormData());
    }
  },
);

function handleUpdateShow(value: boolean) {
  emits('update:show', value);
}

function handleSave() {
  saveBtnLoading.value = true;
  formRef.value
    ?.validate()
    .then(() => {
      roleSav(formData).then((data: BMPCH.RoleSavOutput) => {
        if (data.success) {
          formData.roleId = data.roleId;
          handleUpdateShow(false);
          window.$message.success('保存成功');
          emits('refresh');
        } else {
          window.$message.error(data.errmsg);
        }
      });
    })
    .catch(() => {
      window.$message.error('请填写完整信息');
    })
    .finally(() => {
      saveBtnLoading.value = false;
    });
}

function handleUpdateDfltFlg(value: string) {
  formData.dfltFlg = value;
}
</script>

<style lang="less" scoped></style>
